package znet

import (
	"fmt"
	"github.com/zinx/ziface"
)

/**
消息处理模块实现
*/

type MsgHandle struct {
	// 存放msgid对应的处理方法
	Apis map[uint32]ziface.IRouter
}

// 执行对应的router消息处理方法
func (mh *MsgHandle) DoMsgHandler(request ziface.IRequest) {
	// 获取请求id

	router, ok := mh.Apis[request.GetMsgId()]
	if !ok {
		fmt.Println("api msgId is not exist")
		return
	}
	router.PreHandle(request)
	router.Handle(request)
	router.PostHandle(request)
}

// 添加对应的处理路由
func (mh *MsgHandle) AddRouter(msgId uint32, router ziface.IRouter) {
	if _, ok := mh.Apis[msgId]; ok {
		panic(fmt.Sprintf("repeat api msgid =%d", msgId))
	}
	mh.Apis[msgId] = router
}

// 创建MsgHandle 方法
func NewMsgHandle() *MsgHandle {
	return &MsgHandle{
		Apis: make(map[uint32]ziface.IRouter),
	}
}
